package io.renren.modules.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.member.dao.StandardBmiDao;
import io.renren.modules.member.entity.ExamEntity;
import io.renren.modules.member.entity.MemberEntity;
import io.renren.modules.member.entity.StandardBmiEntity;
import io.renren.modules.member.service.StandardBmiService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;
import java.util.Objects;

@Service
public class StandardBmiServiceImpl extends ServiceImpl<StandardBmiDao, StandardBmiEntity> implements StandardBmiService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String sex = (String) params.get("sex");

        IPage<StandardBmiEntity> page = this.page(
                new Query<StandardBmiEntity>().getPage(params),
                new QueryWrapper<StandardBmiEntity>()
                        .eq(StringUtils.isNotBlank(sex), "sex", sex)
        );
        return new PageUtils(page);
    }

    public String getBmiSorce(ExamEntity examEntity, MemberEntity memberEntity) {
        if (Objects.isNull(examEntity.getAge()) || examEntity.getAge() < 1
                || Objects.isNull(examEntity.getHeight()) || examEntity.getHeight().compareTo(BigDecimal.ZERO) != 1
                || Objects.isNull(examEntity.getWeight()) || examEntity.getWeight().compareTo(BigDecimal.ZERO) != 1) {
            return null;
        }
        StandardBmiEntity bmiEntity = baseMapper.findBySexAndAge(memberEntity.getSex(), examEntity.getAge());
        if (Objects.isNull(bmiEntity)) {
            return null;
        }
        BigDecimal height = examEntity.getHeight().divide(new BigDecimal("100"), 2, BigDecimal.ROUND_DOWN);
        BigDecimal result = examEntity.getWeight().divide(height.multiply(height), 2, BigDecimal.ROUND_DOWN);
        examEntity.setBmi(result);
        if (result.compareTo(bmiEntity.getMinBmi()) != -1 && result.compareTo(bmiEntity.getMaxBmi()) != 1 ) {
            return "1";
        } else {
            return "0";
        }
    }
}
